package com.glodon.paas.qto.resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.job.JobConstants;
import com.glodon.paas.job.exception.JsonException;
import com.glodon.paas.job.model.TaskStatus;
import com.glodon.paas.job.util.JsonUtil;
import com.glodon.paas.qto.model.TaskProgress;
import com.glodon.paas.qto.service.QtoService;

@Component
@Path("/task")
public class TaskResource {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private QtoService qtoService;

    @SuppressWarnings("rawtypes")
    @PUT
    @Path("/{taskId}")
    @Produces(MediaType.APPLICATION_JSON)
    public String processTaskNotify(@PathParam("taskId") String taskId, InputStream is) throws IOException {
        String body = IOUtils.toString(is);
        logger.debug("receive task notify:{}", body);
        Map map = null;
        try {
            map = JsonUtil.jsonToMap(body);
        } catch (JsonException e) {
            throw PaasServerExceptionFactory.validateException("bad json string from job-server", e);
        }
        TaskProgress task = new TaskProgress();
        task.setTaskId(taskId);
        String status = (String) map.get(JobConstants.PROPERTY_TASK_STATUS);
        if (StringUtils.isEmpty(status)) {
            throw PaasServerExceptionFactory.validateException("status cann't be empty", null);
        }
        task.setProgress((Integer) ((Map)map.get("values")).get("progress"));
        task.setMessage((String)((Map)map.get("values")).get(JobConstants.TASK_MESSAGE));
        task.setStatus(Enum.valueOf(TaskStatus.class, status));
        task.setOutput((String)((Map)map.get("values")).get(JobConstants.OUTPUT));
        task.setFilename((String)((Map)map.get("values")).get(JobConstants.PROPERTY_TASK_FILE_NAME));
        logger.info("receive notify task:{}", task);
        boolean jobComplete = qtoService.processTaskNotify(taskId, task);
        return Boolean.toString(jobComplete);
    }
}
